package core.dispatch.event.room;

import business.global.club.ClubMember;
import business.global.club.ClubMgr;
import business.global.shareclub.ShareClubMemberMgr;
import business.global.shareclub.SharePromotionSectionMgr;
import business.global.shareunion.ShareUnionListMgr;
import business.global.union.Union;
import business.global.union.UnionMgr;
import business.shareplayer.ShareLeavePlayerMgr;
import cenum.ConstEnum;
import cenum.DispatcherComponentEnum;
import cenum.ItemFlow;
import com.ddm.server.common.CommLogD;
import com.ddm.server.common.Config;
import com.ddm.server.common.utils.CommMath;
import com.ddm.server.common.utils.CommTime;
import com.ddm.server.dispatcher.executor.BaseExecutor;
import core.db.entity.clarkGame.ClubMemberXiFen;
import core.db.entity.clarkGame.UnionDynamicBO;
import core.db.other.Restrictions;
import core.db.service.clarkGame.ClubMemberRelationBOService;
import core.db.service.clarkGame.PromotionLevelRoomConfigScorePercentBOService;
import core.db.service.clarkGame.UnionRoomConfigScorePercentBOService;
import core.db.service.clarkGame.UnionShareSectionBOService;
import core.ioc.ContainerMgr;
import core.logger.flow.FlowLogger;
import jsproto.c2s.cclass.club.ClubRoomPosInfoZhongZhi;
import jsproto.c2s.cclass.club.PromotionShareSectionItem;
import jsproto.c2s.cclass.club.QueryUidOrPuidItem;
import jsproto.c2s.cclass.club.SharePromotionSection;
import jsproto.c2s.cclass.union.UnionDefine;
import jsproto.c2s.cclass.union.UnionShareSectionItem;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Data
public class RoomXiFenShare implements BaseExecutor {
    private double xiFen;
    /**
     * 赛事id
     */
    private long unionId;

    /**
     * 亲友圈ID
     */
    private long clubId;
    /**
     * 房间名称
     */
    private String roomName;
    /**
     * 房间号
     */
    private int roomKey;
    /**
     * 配置Id
     */
    private long configId;
    /**
     * 房间id
     */
    private long roomId;

    /**
     * ID
     */
    private int Id;
    /**
     * 城市Id
     */
    private int cityId;
    /**
     * 收益类型
     */
    private int sourceType = 2;
    /**
     * 时间
     */
    private String dateTime;
    /**
     * 对局数
     */
    private int setCount;
    /**
     * 房间配置
     */
    private String dataJsonCfg;
    /**
     * 游戏类型
     */
    private int gameId;
    /**
     是否分成到保险箱
     */
    private boolean caseSportsFlag;
    //百分比计算控制值
    private double scorePercentCalc;
    /**
     * 亲友圈圈主分成值
     * key 圈主id
     * value 圈主获得的值
     */
    private Map<Long,Double> clubOwnerProfit=new HashMap<>();
    /**
     * 联赛类型
     */
    private UnionDefine.UNION_TYPE unionType=UnionDefine.UNION_TYPE.NORMAL;


    public RoomXiFenShare(double xiFen, long unionId, long clubId, String roomName, int roomKey, long configId, long roomId, int id,  int cityId,String dateTime, String dataJsonCfg, int setCount, int gameId) {
        this.xiFen=xiFen;
        this.unionId = unionId;
        this.clubId=clubId;
        this.roomName = roomName;
        this.roomKey = roomKey;
        this.configId = configId;
        this.roomId = roomId;
        Id = id;
        this.cityId = cityId;
        this.dateTime = dateTime;
        this.setCount = setCount;
        this.dataJsonCfg = dataJsonCfg;
        this.gameId = gameId;
    }

    @Override
    public void invoke() {
        //计算值初始化
        if (this.getXiFen() <= 0D) {
            return;
        }
        //检查是否有开启分成走保险箱功能
        this.checkCaseSpointFlag();
        // 获取亲友圈成员信息
        ClubMember create;
        if(Config.isShare()){
            create = ShareClubMemberMgr.getInstance().getClubMember(UnionMgr.getInstance().getUnionMemberMgr().findCreateClubMemberId(this.getUnionId()));
        } else {
            create = ClubMgr.getInstance().getClubMemberMgr().getClubMemberMap().get(UnionMgr.getInstance().getUnionMemberMgr().findCreateClubMemberId(this.getUnionId()));
        }

        //计算分成后剩下的喜分 pvc
        double sumValue = this.clubSportsPointProfit();

        if (Objects.nonNull(create)) {
            // 盟主获取的收益
            int execType = caseSportsFlag ? UnionDefine.UNION_EXEC_TYPE.UNION_EXEC_PROMOTION_XIFEN_INCOME_CASEPOINT.value() : UnionDefine.UNION_EXEC_TYPE.UNION_EXEC_PROMOTION_XIFEN_INCOME.value();
            saveUnionSportsPointProfitUnion(create,this.getUnionId(), this.getXiFen(), this.getSourceType(), this.getRoomName(), this.getRoomKey(), getId(), this.getCityId(), ConstEnum.ResOpType.Gain, this.getRoomId(),clubOwnerProfit);
            if(sumValue > 0){
                saveUnionSportsPointProfitUnion(create,this.getUnionId(), -sumValue, this.getSourceType(), this.getRoomName(), this.getRoomKey(), getId(), this.getCityId(), ConstEnum.ResOpType.Lose, this.getRoomId(),clubOwnerProfit);
            }
//            UnionDynamicBO.insertRoomSportsPoint(create.getClubMemberBO().getPlayerID(), create.getClubID(), CommTime.nowSecond(), execType, this.getUnionId(), String.valueOf(this.getXiFen()),String.valueOf(create.getClubMemberBO().getSportsPoint()), String.valueOf(this.getRoomKey()));

            ShareLeavePlayerMgr.getInstance().addLeaveSharePlayer(create.getClubID(), create.getClubMemberBO().getPlayerID(), roomId, this.getXiFen());
        } else {
            //添加日志 报空
            CommLogD.error("clubMemberUnionCreate  is null :{},this.getXiFen():{}",this.toString(),this.getXiFen());
        }
    }

    /**
     * 亲友圈分成收益
     *
     * @return
     */
    private double clubSportsPointProfit() {
        double sumValue = 0D;
        ClubMember clubMember = null;
        //当前房间 每个人的贡献的竞技点
        double perConsume = 0D;
        ClubMember clubMemberUnionCreate = ShareClubMemberMgr.getInstance().getClubMember(UnionMgr.getInstance().getUnionMemberMgr().findCreateClubMemberId(this.getUnionId()));
        double oneClubXiFenTotal = ShareClubMemberMgr.getInstance().getOneClubXiFenTotal(clubMemberUnionCreate.getClubID());
        if(oneClubXiFenTotal > 0){
            List<ClubMemberXiFen> oneClubMemberXiFenSetList = ShareClubMemberMgr.getInstance().getOneClubMemberXiFenSetList(clubMemberUnionCreate.getClubID());
            if(CollectionUtils.isNotEmpty(oneClubMemberXiFenSetList)){
                for(ClubMemberXiFen xiFen : oneClubMemberXiFenSetList){
                    clubMember = ShareClubMemberMgr.getInstance().getClubMember(xiFen.getMemberId());

                    if (Objects.nonNull(clubMember)) {
                        // 盟主分给圈主的   先计算走  然后再算推广员之间的分成
                        double value = 0D;//分成推广员的喜分

                        // 盟主分给圈主的 百分比
                        double scorePercent = CommMath.divThreePoint(xiFen.getXifenValue(), 100);//获取百分比
                        value = CommMath.mul(scorePercent, getXiFen());

                        //圈主们一共获得的收益
                        sumValue = CommMath.addDouble(sumValue, value);
                        this.saveUnionSportsPointProfitPromotion(clubMember,this.getUnionId(), value, this.getSourceType(), this.getRoomName(), this.getRoomKey(), getId(),this.getCityId(), ConstEnum.ResOpType.Gain, this.getRoomId(), dateTime, clubMember.getClubMemberBO().getPlayerID(), clubMemberUnionCreate.getClubMemberBO().getPlayerID());
                    } else {
                        //添加日志 判断是否亲友圈 圈住id 为0
                        CommLogD.error("RoomXiFenShare clubCreateId is null one " + xiFen.getMemberId());
                    }
                }
            }
        }else{
            sumValue = getXiFen();
        }
        return sumValue;
    }


    /**
     * 检查是否有开启分成走保险箱功能
     */
    public void  checkCaseSpointFlag(){
        Union union;
        if(Config.isShare()){
            union = ShareUnionListMgr.getInstance().getUnion(this.getUnionId());
        } else {
            union = UnionMgr.getInstance().getUnionListMgr().findUnion(this.getUnionId());
        }
        if(UnionDefine.UNION_CASE_STATUS.OPEN.ordinal()==union.getUnionBO().getShareStatus()){
            this.setCaseSportsFlag(true);
        }
        this.setUnionType(UnionDefine.UNION_TYPE.valueOf(union.getUnionBO().getUnionType()));
    }



    /**
     盟主获得
     */
    public void saveUnionSportsPointProfitUnion(ClubMember clubMember,long unionId, double value, int sourceType, String roomName, int roomKey, int gameId, int cityId, ConstEnum.ResOpType resOpType, long roomId,Map<Long,Double> clubOwnerProfit) {
        if(this.caseSportsFlag){
            //如果是扣分的话要考虑 保险箱分数不低于0  不足的 从竞技点去扣   4  -5
            if(value<0){
                double casePoint=clubMember.getClubMemberBO().getCaseSportsPoint();
                double subValue=CommMath.addDouble(casePoint,value);
                if(subValue<0){
                    clubMember.getClubMemberBO().saveUnionSportsPointProfitToCasePoint(unionId,-casePoint, sourceType, roomName, roomKey, gameId, cityId,resOpType, roomId,true,clubOwnerProfit,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT_CASEPOINT);
                    clubMember.getClubMemberBO().saveUnionSportsPointProfit(unionId,subValue, sourceType, roomName, roomKey, gameId, cityId,resOpType, roomId,false,clubOwnerProfit,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT);
                    return;
                }
            }
            clubMember.getClubMemberBO().saveUnionSportsPointProfitToCasePoint(unionId,value, sourceType, roomName, roomKey, gameId, cityId,resOpType, roomId,true,clubOwnerProfit,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT_CASEPOINT);
        }else {
            clubMember.getClubMemberBO().saveUnionSportsPointProfit(unionId,value, sourceType, roomName, roomKey, gameId, cityId,resOpType, roomId,true,clubOwnerProfit,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT);
        }
    }
    /**
     *推广员获得
     */
    public void saveUnionSportsPointProfitPromotion(ClubMember clubMember,long unionId, double value, int sourceType, String roomName, int roomKey, int gameId, int cityId, ConstEnum.ResOpType resOpType, long roomId, String dateTime,long execPid,long reasonPid) {
        if(this.caseSportsFlag){
            //如果是扣分的话要考虑 保险箱分数不低于0  不足的 从竞技点去扣   4  -5
            if(value<0){
                double casePoint=clubMember.getClubMemberBO().getCaseSportsPoint();
                double subValue=CommMath.addDouble(casePoint,value);
                if(subValue<0){
                    clubMember.getClubMemberBO().saveUnionSportsPointProfitPromotionToCasePoint(unionId,-casePoint,sourceType,roomName,roomKey,gameId,cityId,resOpType,roomId,dateTime,execPid,reasonPid,null,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT_CASEPOINT);
                    clubMember.getClubMemberBO().saveUnionSportsPointProfitPromotion(unionId,subValue,sourceType,roomName,roomKey,gameId,cityId,resOpType,roomId,dateTime,execPid,reasonPid,null,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT);
                    return;
                }
            }
            clubMember.getClubMemberBO().saveUnionSportsPointProfitPromotionToCasePoint(unionId,value,sourceType,roomName,roomKey,gameId,cityId,resOpType,roomId,dateTime,execPid,reasonPid,null,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT_CASEPOINT);
        }else {
            clubMember.getClubMemberBO().saveUnionSportsPointProfitPromotion(unionId,value,sourceType,roomName,roomKey,gameId,cityId,resOpType,roomId,dateTime,execPid,reasonPid,null,clubMember.getClubMemberBO().isZhongZhiClub(), ItemFlow.PROMOTION_SPORTS_XIFEN_PROFIT);
        }
    }



    /**
     * 判断是不是中至亲友圈
     * @return
     */
    public boolean isZhongZhiUnion(){
        Union union = UnionMgr.getInstance().getUnionListMgr().findUnion(this.getUnionId());
        if(Objects.isNull(union)){
            return false;
        }
        return union.getUnionBO().getUnionType()==UnionDefine.UNION_TYPE.ZhongZhi.value();
    }

    @Override
    public int threadId() {
        return DispatcherComponentEnum.PROMOTION_SHARE.id();
    }

    @Override
    public int bufferSize() {
        return DispatcherComponentEnum.PROMOTION_SHARE.bufferSize();
    }

    @Override
    public String toString() {
        return "RoomPromotionShare{" +
                ", xiFen=" + xiFen +
                ", unionId=" + unionId +
                ", clubId=" + clubId +
                ", roomName='" + roomName + '\'' +
                ", roomKey=" + roomKey +
                ", configId=" + configId +
                ", roomId=" + roomId +
                ", Id=" + Id +
                ", cityId=" + cityId +
                ", sourceType=" + sourceType +
                ", dateTime='" + dateTime + '\'' +
                ", setCount=" + setCount +
                ", dataJsonCfg='" + dataJsonCfg + '\'' +
                ", gameId=" + gameId +
                '}';
    }
}
